package com.bdb.myswipemultitype.swipeListview.swipeMenuRecycle;

import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.bdb.myswipemultitype.R;

import java.util.List;

import me.drakeet.multitype.MultiTypeAdapter;

/**
 * Created by zinc on 2017/5/15.
 */

public class SwipeAdapter extends MultiTypeAdapter {

    private SwipeListener listener;
    private int menuId = 0;
    private int layoutId = 0;
    private List items;

    public SwipeAdapter(@Nullable List<?> items) {
        super(items);
        this.items = items;
    }

    public void setMenuId(int menuId) {
        this.menuId = menuId;
    }

    public void setLayoutId(int layoutId) {
        this.layoutId = layoutId;
    }

    public void setListener(SwipeListener listener) {
        this.listener = listener;
    }

    @Override
    public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position, final List<Object> payloads) {
        super.onBindViewHolder(holder,position,payloads);

        TextView menu;

        if(menuId != 0) {

            SwipeItemLayout swipeItemLayout = (SwipeItemLayout)holder.itemView.findViewById(R.id.swipe);
            Object tag = holder.itemView.getTag(R.integer.menuListener);

            MenuClickMenuListener menuListener = null;

            if(tag != null){

                Log.i("menu", "old");
                menuListener = (MenuClickMenuListener) tag;

            }else{

                Log.i("menu", "new");
                menuListener = new MenuClickMenuListener(swipeItemLayout, position);

                holder.itemView.setTag(R.integer.menuListener, menuListener);

            }

            menu = (TextView) holder.itemView.findViewById(menuId);
            if(menu != null){
                menuListener.setPosition(position);
                menu.setOnClickListener(menuListener);
            }
        }

    }

    public interface SwipeListener{
        void menuClick(View v, int position);
    }

    class MenuClickMenuListener implements View.OnClickListener {

        private SwipeItemLayout swipeItemLayout;
        private int position;

        public MenuClickMenuListener(SwipeItemLayout swipeItemLayout, int position) {
            this.swipeItemLayout = swipeItemLayout;
            this.position = position;
        }

        public void setSwipeItemLayout(SwipeItemLayout swipeItemLayout) {
            this.swipeItemLayout = swipeItemLayout;
        }

        public void setPosition(int position) {
            this.position = position;
        }

        @Override
        public void onClick(View v) {
            if(layoutId != 0 && listener!=null){
                listener.menuClick(v, position);
                swipeItemLayout.close();
            }
        }

    }

}
